package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class EchoHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        PrintWriter writer = new PrintWriter(response);
        Map<String, String> params = request.getAllParams();

        StringBuilder contentBuilder = new StringBuilder();
        contentBuilder.append("Echo Server Response\n");
        contentBuilder.append("====================\n");
        contentBuilder.append("Request Details:\n");
        contentBuilder.append("Method: ").append(request.getMethod()).append("\n");

        // 根据接收到的参数Map构建文本列表，回显给客户端
        if (params.isEmpty()) {
            contentBuilder.append("No Parameters Received.\n");
        } else {
            contentBuilder.append("Received Parameters:\n");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                contentBuilder.append("- ").append(entry.getKey())
                        .append(": ").append(entry.getValue()).append("\n");
            }
        }

        String content = contentBuilder.toString();
        byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);

        // TODO: [222024321072050/邓琳馨] 构造完整的 HTTP 响应头

        writer.println("HTTP/1.1 200 OK");
        writer.println("Content-Type: text/plain; charset=UTF-8");
        writer.println("Content-Length: " + contentBytes.length);
        writer.println("Connection: close");
        writer.println();

        writer.print(content);
        writer.flush();
    }
}